export type CheckboxGroupOption = {
  label: string
  value: string | number
  disabled: boolean
}

function useCheckboxGroup(options?: {defaultOptions: CheckboxGroupOption[]}) {
  const checkboxGroupOptions = ref<CheckboxGroupOption[]>(options?.defaultOptions || [])
  function setCheckboxGroupOptions(data: CheckboxGroupOption[]) {
    checkboxGroupOptions.value = data
  }
  const getCheckboxGroupOptions = computed(() => checkboxGroupOptions.value)

  /**
   * 重新组合成checkboxGroup需要的列表格式
   * @param option
   * @returns
   */
  function updateCheckboxGroup<T extends {[key: string]: string}>(option: {
    list: T[]
    labelKey: keyof T
    valueKey: keyof T
    poll?: (data: T) => boolean
  }): CheckboxGroupOption[] {
    const {labelKey, valueKey, list, poll} = option

    const returnArr: CheckboxGroupOption[] = []

    for (let i = 0; i < list.length; i++) {
      const item = list[i]

      // 是否禁用
      let disabled = false
      poll && (disabled = poll(item))

      returnArr.push({
        value: item[valueKey],
        label: item[labelKey],
        disabled
      })
    }
    setCheckboxGroupOptions(returnArr)
    return returnArr
  }

  return {
    updateCheckboxGroup,
    checkboxGroupList: getCheckboxGroupOptions,
    setCheckboxGroupOptions
  }
}

export default useCheckboxGroup
